/**
 * Copyright 2016-2018 mobaas.com
 */
package com.mobaas.devops.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mobaas.devops.PageList;
import com.mobaas.devops.dao.WebUrlDao;
import com.mobaas.devops.model.NotifyKind;
import com.mobaas.devops.model.WebUrl;
import com.mobaas.devops.model.WebUrlLog;
import com.mobaas.devops.service.NotificationService;
import com.mobaas.devops.service.WebUrlService;

/**
 * 
 * @author billy zhang
 * 
 */
@Service
public class WebUrlServiceImpl implements WebUrlService {

	@Autowired
	private WebUrlDao weburlDao;

	@Autowired
	private NotificationService notiService;
	
	@Override
	public List<WebUrl> selectWebUrlList(int state) {

		return weburlDao.selectWebUrlList(state);
	}

	@Override
	public int updateWebUrl(WebUrl url) {
		return weburlDao.updateWebUrl(url);
	}
	
	@Override
	public PageList<WebUrlLog> selectWebUrlLogList(int urlId, int pageNum, int pageSize) {
		PageList<WebUrlLog> pi = new PageList<>();
		pi.setPageNo(pageNum);
		pi.setPageSize(pageSize);
		pi.setTotal( weburlDao.selectWebUrlLogCount(urlId) );
		pi.setList( weburlDao.selectWebUrlLogList(urlId, (pageNum-1) * pageSize, pageSize) );
		
		return pi;
	}

	@Override
	public void insertWebUrlLog(WebUrlLog log) {
		weburlDao.insertWebUrlLog(log);
		
		WebUrl url = weburlDao.selectWebUrlById(log.getUrlId());
		url.setLastStatus( log.getScanStatus() );
		url.setLastScanTime( log.getScanTime() );
		
		if (log.getScanStatus() == 200) {
			url.setLastErrCount(0);  // 访问正常了，归零
		} else {
			url.setLastErrCount( url.getLastErrCount()+1 );
			if (url.getLastErrCount() > 5) {  // TODO: 规则重构
				notiService.notify(NotifyKind.WebUrl, "WebUrl扫描警报", url.getUrl() + " is DOWN.");  
				url.setLastErrCount(1);
			}
		}
		weburlDao.updateWebUrl(url);
	}

	@Override
	public int clearWebUrlLogs(Date beforeDate) {
		
		return weburlDao.deleteWebUrlLogs(beforeDate);
	}

}
